import { lowerCase } from 'lodash'
import { Assist, FileUtil } from '@libs/lhy-common'
import i18n from '@libs/lhy-common/i18n'
import { ArgumentMetadata, Injectable, Optional, PipeTransform } from '@nestjs/common'

@Injectable()
export class ParseFilePipe<CONFIG extends ParseFilePipeOption = ParseFilePipeOption>
  implements PipeTransform<Express.Multer.File, Express.Multer.File>
{
  /**
   * 默认单文件大小
   */
  static readonly SINGLE_FILE_SIZE = 100

  constructor(@Optional() protected option?: CONFIG) {}

  transform(value: Express.Multer.File, metadata: ArgumentMetadata) {
    this.validateFileSize(value)
    this.validateExts(value)

    return value
  }

  /**
   * 校验文件大小
   * @param file
   */
  protected validateFileSize(file: Express.Multer.File) {
    const singleFileSize = this.option?.singleFileSize || ParseFilePipe.SINGLE_FILE_SIZE

    Assist.threw(
      file.size > singleFileSize * 1024 * 1024,
      i18n.t('lhy-core.parse-file.parse-file.1214951-0', { args: [singleFileSize] })
    )
  }

  /**
   * 校验文件后缀
   * @param file
   * @returns
   */
  protected validateExts(file: Express.Multer.File) {
    if (!this.option?.exts?.length) {
      return
    }

    const exts = this.option.exts.map(lowerCase)
    const fileExt = lowerCase(FileUtil.getFileExt(file))

    Assist.threw(
      !exts.includes(fileExt),
      i18n.t('lhy-core.parse-file.parse-file.1214951-1', { args: [exts.join(', ')] })
    )
  }
}

export interface ParseFilePipeOption {
  /**
   * 单文件大小，默认100。单：MB
   */
  singleFileSize?: number
  /**
   * 文件后缀名，不区分大小写，默认不限制
   */
  exts?: string[]
}
